package com.dps.omc.agent.queue.consumer.tasker;

import com.dps.omc.agent.queue.consumer.tasker.utils.JschClient;
import com.dps.omc.agent.queue.consumer.tasker.utils.WindowsTelnetHelper;
import com.dps.omc.agent.queue.producer.SendTasker;
import com.dps.omc.task.message.EnumMsgType;
import com.dps.omc.task.message.EnumTaskNodeType;
import com.dps.omc.task.message.EnumTaskState;
import com.dps.omc.task.message.TaskMessage;
import com.jcraft.jsch.JSchException;
import net.sf.json.JSONObject;
import org.apache.commons.exec.OS;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketException;

/**
 * Created by lip on 2015-12-17.
 */
public class CommandRecTasker extends AbstractRecTasker{

    private static final Logger logger = LoggerFactory.getLogger(CommandRecTasker.class);

    public CommandRecTasker(String message) {
        super(message);
    }

    @Override
    public void execute() throws Exception {
        String msg = this.getMessage();
        TaskMessage taskMessage = this.getTaskMessage(msg);

        if (taskMessage.getTaskNodeType().equals(EnumTaskNodeType.TELNET)) {
            this.executeOnWindows(taskMessage);
        } else if (OS.isFamilyUnix()) {
            this.executeOnUnix(taskMessage);
        } else {
            logger.info("不支持该操作系统");
        }
    }

    private void executeOnWindows(TaskMessage taskMessage) throws Exception {
//        logger.info("taskMessage:"+taskMessage.toString());
        String host = null;
        String user = null;
        String pass = null;

        host = taskMessage.getServerIp();
        user = taskMessage.getServerUser();
        pass = taskMessage.getServerPass();
        String returnMsg = "";

        WindowsTelnetHelper wth = null;
        try {
            wth = new WindowsTelnetHelper(host, user, pass);
            if(wth.connectToHost()){
                wth.initIO(null);
                if(wth.login()){
                    String res = wth.execCommand(taskMessage.getCmdShell());
                    returnMsg = StringUtils.isNotBlank(res)?res:"";
                }
            }

        } catch (SocketException e) {
            this.connectFail(taskMessage,e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            this.connectFail(taskMessage,e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if(wth!=null)
            {
                wth.destroy();
            }
        }
//        Integer msgMaxSize = Constants.RETURN_MSG_MAXSIZE;
//        returnMsg = returnMsg.length()>msgMaxSize?returnMsg.substring(0,msgMaxSize):returnMsg;
        taskMessage.setReturnMsg(returnMsg);
        taskMessage.setTaskState(EnumTaskState.SUCC);
        SendTasker.sendMessage(taskMessage);
    }

    public void executeOnUnix(TaskMessage taskMessage) throws Exception {

        String host = null;
        String user = null;
        String pass = null;

        if(taskMessage.isServerConn())
        {
            host = taskMessage.getServerIp();
            user = taskMessage.getServerUser();
            pass = taskMessage.getServerPass();
        }
        else
        {
            host = taskMessage.getClientIp();
            user = taskMessage.getSysUser();
            pass = taskMessage.getSysPass();
        }
        JschClient client = new JschClient(user,pass,host);
        try {
            client.connect();
        } catch (JSchException e) {
            this.connectFail(taskMessage,e.toString());
            e.printStackTrace();
        }
        String returnMsg = client.execCmd(this.processCmd(taskMessage.getCmdShell()));
//        Integer msgMaxSize = Constants.RETURN_MSG_MAXSIZE;
//        returnMsg = returnMsg.length()>msgMaxSize?returnMsg.substring(0,msgMaxSize):returnMsg;
        taskMessage.setReturnMsg(returnMsg);
        taskMessage.setTaskState(EnumTaskState.SUCC);
        SendTasker.sendMessage(taskMessage);
    }

    private String processCmd(String cmd)
    {
        String shell = cmd.replaceAll("\r","").replaceAll("\n","");
        return shell;
    }

    private TaskMessage getTaskMessage(String msg) throws Exception {
        JSONObject jsonObject = JSONObject.fromObject(msg);
        JSONObject obj = jsonObject.getJSONObject("taskMessage");
        TaskMessage tm = new TaskMessage();
        tm.setTaskId(obj.getString("taskId"));
        tm.setCmdShell(obj.getString("cmdShell"));
        tm.setAgentId(obj.getString("agentId"));
        tm.setClientIp(obj.getString("clientIp"));
        tm.setSysUser(obj.getString("sysUser"));
        tm.setSysPass(obj.getString("sysPass"));
        tm.setMsgType(EnumMsgType.valueOf(obj.getString("msgType")));
        tm.setReturnMsg(obj.getString("returnMsg"));
        tm.setTaskState(EnumTaskState.valueOf(obj.getString("taskState")));
        tm.setServerIp(obj.getString("serverIp"));
        tm.setServerUser(obj.getString("serverUser"));
        tm.setServerPass(obj.getString("serverPass"));
        tm.setServerConn(obj.getString("serverConn").equals("true")?true:false);
        tm.setTaskNodeType(EnumTaskNodeType.valueOf(obj.getString("taskNodeType")));
//        processTaskMessageByPass(tm);
        return tm;
    }

    //服务器账号密码错误是返回错误
    private void connectFail(TaskMessage taskMessage,String returnMsg) throws Exception {
        taskMessage.setReturnMsg(returnMsg);
        taskMessage.setTaskState(EnumTaskState.FAIL);
        SendTasker.sendMessage(taskMessage);
    }


//    public static void main(String[] args) throws Exception {
//        String msg = "mysql -h 10.238.6.92 -ulp -plp testrms</root/1.sql";
////        String msg = "pwd";
//        CommandRecTasker tasker = new CommandRecTasker(msg);
//        tasker.executeOnUnix(msg);
//    }
}
